package com.spring.service;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.spring.web.formbean.Form;

public class ServiceSupport {
	/**
	 * 把form对象转换成实体对象
	 * @param <T>
	 * @param beanClass
	 * @param formBean
	 * @return
	 */
	protected <T> T formToEntity(Class<T> beanClass,Form formBean){
		try{
			T bean = beanClass.newInstance();
			return formToEntity(bean,formBean);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 把已经存在的entity重新用form填充，formBean的属性值为空时，就不填充
	 * @param <T>
	 * @param entity
	 * @param formBean
	 * @return
	 */
	protected <T> T formToEntity(T entity, Form formBean){
		try {
			Map formMap = BeanUtils.describe(formBean);
			Iterator<String> properties = formMap.keySet().iterator();
			while(properties.hasNext()){
				String prop = properties.next();
				Object o = BeanUtils.getProperty(formBean, prop);
				//这里不使用copyProperties方法的原因是对于null类型的数据有特殊转变，
				//如Integer为null时，设置为0,而PropertyUtils又不支持类型转换
				if( o==null || !PropertyUtils.isWriteable(entity, prop) )
					continue ;

				BeanUtils.copyProperty(entity, prop, o);
			}	
			
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
